package com.itqf.controller;
import com.itqf.entity.Users;
import com.itqf.enums.MyEnums;
import com.itqf.utils.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 作者：杨超波
 * 时间：2019/12/4  20:41
 * 描述：
 */
@RestController
@RequestMapping("user")
public class UserController {
    @PostMapping("login")
    public R login(String username, String password){
        if (username == null || password ==null){
            return R.error(MyEnums.PARAMETER_ERROR);
        }
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return R.error(MyEnums.USERNAME_ERROR);
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return R.error(MyEnums.PASSWORD_ERROR);
        }catch (Exception e){
            e.printStackTrace();
            return R.error(MyEnums.NOT_KNOW_ERROR);
        }
        return R.ok("登录成功",null);
    }
    @GetMapping("info")
    public R info(){
        Subject subject = SecurityUtils.getSubject();
        Users user = (Users) subject.getPrincipal();
        if (user==null){
            return R.error(MyEnums.USER_NOT_LOGIN);
        }
        return R.ok("成功",user.getName());
    }
}
